<?php
namespace app\shop\model;
use app\rbac\model\AdminM;
use think\Request;
use think\Validate;
use think\Db;
use app\base\model\Base;
class GoodsM extends Base
{

       protected function _V($scene,$data)
       {
           $rule = [
               'goods_name' => 'require',
               'goods_sn' => 'require',
               'ps_attr' => 'require|number',
               'psfs_id' => 'require|number',
               'brand_id' => 'require|number',
               'cat_id' => 'require|number',
               'type_id' => 'require|number',
               'is_new' => 'require|number',
               'is_hot' => 'require|number',
               'is_best' => 'require|number',
               'is_floor' => 'require|number',
               'shop_id' => 'require|number',
               'is_discount' => 'require|number',
               'sort_num' => 'require|number',
               'attr_value' => 'require',
           ];
        $msg = [];
        $filed = [
            'goods_name'=>'商品名称',
            'goods_desc'=>'商品详情',
            'goods_sn'=>'商品货号',
            'ps_attr'=>'配送属性',
            'psfs_id'=>'配送方式',
            'brand_id'=>'品牌',
            'cat_id'=>'主分类',
            'type_id'=>'类型',
            'is_new'=>'是否新品',
            'is_hot'=>'是否热卖',
            'is_best'=>'是否精品',
            'is_floor'=>'是否推荐',
            'shop_id'=>'店铺',
            'is_discount'=>'是否折扣',
            'sort_num'=>'排序',
            'attr_value'=>'商品属性',
        ];
           $validate = new Validate($rule,$msg,$filed);
           $validate->scene('add', ['goods_name','goods_desc','goods_sn','ps_attr','psfs_id','brand_id','cat_id','type_id','is_new','is_hot','is_best','is_floor','shop_id','is_discount','sort_num','attr_value']);
           $validate->scene('edit', ['goods_name','goods_desc','goods_sn','ps_attr','psfs_id','brand_id','cat_id','type_id','is_new','is_hot','is_best','is_floor','shop_id','is_discount','sort_num','attr_value']);
           $result = $validate->scene($scene)->check($data);
           if($result === false)
           {
               return $validate->getError();
           }
           else
           {
               return true;
           }

       }

    /**
     * 新增数据
     * @return mixed
     */

    public function add($data)
    {
        //验证数据
        $res = $this->_V('add',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        $insertData = [];
        //判断用户
        $admin_id = session('admin_id');
        $insertData['admin_id'] = $admin_id;
        //数据
        $insertData['goods_name'] = $data['goods_name'];
        $insertData['goods_sn'] = $data['goods_sn'];
        $insertData['ps_attr'] = $data['ps_attr'];
        $insertData['psfs_id'] = $data['psfs_id'];
        $insertData['brand_id'] = $data['brand_id'];
        $insertData['cat_id'] = $data['cat_id'];
        $insertData['type_id'] = $data['type_id'];
        $insertData['is_new'] = $data['is_new'];
        $insertData['is_hot'] = $data['is_hot'];
        $insertData['is_best'] = $data['is_best'];
        $insertData['is_floor'] = $data['is_floor'];
        $insertData['shop_id'] = $data['shop_id'];
        $insertData['is_discount'] = $data['is_discount'];
        $insertData['is_on_sale'] = $data['is_on_sale'];
        $insertData['sort_num'] = $data['sort_num'];
        if($data['ps_attr'] == 2)
        {
            $insertData['sheng_id'] = $data['sheng_id'];
            $insertData['shi_id'] = $data['shi_id'];
            $insertData['xian_id'] = $data['xian_id'];
            $insertData['coordinate'] = $data['coordinate'];
        }
        //时间
        if(!empty($data['promote_start_date']))
        {
            $insertData['promote_start_date'] = strtotime($data['promote_start_date']);
        }
        if(!empty($data['promote_end_date']))
        {
            $insertData['promote_end_date'] = strtotime($data['promote_end_date']);
        }
        $insertData['created_at'] = time();
        $insertData['updated_at'] = time();
        //主图

        //处理图片
        $ret = uploadOne('logo', array(
            array(800, 800),
            array(600, 600),
            array(300, 300),
            array(100, 100),
        ));
        if($ret['ok'] == 1)
        {
            $insertData['logo'] = toQiNiu($ret['images'][0]);   // 原图地址
            $insertData['mbig_logo'] = toQiNiu($ret['images'][1]);   // 第一个缩略图地址
            $insertData['big_logo'] = toQiNiu($ret['images'][2]);   // 第二个缩略图地址
            $insertData['mid_logo'] = toQiNiu($ret['images'][3]);   // 第三个缩略图地址
            $insertData['sm_logo'] = toQiNiu($ret['images'][4]);   // 第三个缩略图地址
        }
        else if($ret['ok'] == 2)
        {
            $this->code = -1;
            $this->msg = '主图必须上传';
            return false;
        }
        else
        {
            $this->code = -1;
            $this->msg = $ret['error'];
            return false;
        }
        //启动事务
        Db::startTrans();
        //商品插入数据库
            $id = Db::table('shop_goods')->insertGetId($insertData);
            if (!$id) {
                $this->code = -1;
                $this->msg = '新增失败';
                Db::rollback();
                return false;
            }
            //属性
            /*********************处理商品属性-start******************/
            $insertAttr = [];
            foreach ($data['attr_value'] as $k => $v) {
                // 把属性值的数组去重
                $v = array_unique($v);
                foreach ($v as $k1 => $v1) {
                    $insertAttr[] = [
                        'attr_id' => $k,
                        'attr_value' => $v1,
                        'goods_id' => $id,
                        'admin_id' => $admin_id];
                }
            }

            $res = Db::table('shop_goods_attr')->insertAll($insertAttr);
            if (!$res) {
                $this->code = -1;
                $this->msg = '新增属性失败';
                Db::rollback();
                return false;
            }
            /*********************处理商品属性-end******************/
            //图片

            /*********************处理图片相册-start******************/
            if (isset($_FILES['pic']))
            {
                $res = uploadMore('pic',array(
                    array(450, 450),
                    array(260, 260),
                    array(66, 66),
                ));
                if(isset($res['ok']))
                {
                    if($res['ok'] == 0)
                    {//出现错误
                        $this->code = -1;
                        $this->msg = $res['error'];
                        Db::rollback();
                        return false;
                    }
                    else
                    {//没有图片

                    }

                }
                else
                {//上传成功
                    foreach($res as $k=>$v)
                    {
                        $res2 = Db::table('shop_goods_pic')->insertGetId([
                            'goods_id' => $id,
                            'pic' => toQiNiu($v['images'][0]),
                            'small_pic' => toQiNiu($v['images'][3]),
                            'mid_pic' => toQiNiu($v['images'][2]),
                            'big_pic' => toQiNiu($v['images'][1]),
                        ]);
                        if(!$res2)
                        {
                            $this->code = -1;
                            $this->msg = '报存图片到相册失败';
                            Db::rollback();
                            return false;
                        }

                    }

                }
            }
        /*********************处理图片相册-end******************/

        //获取原始数据
        $params = Request::instance()->post(false);
        $time = time();
        //现将默认的商品描述插入
        $_res1 = Db::table('shop_goods_desc')->insertGetId([
            'goods_id'=>$id,
            'desc_name'=>'商品详情',
            'desc_content'=>$params['goods_desc'],
            'sign'=>md5($params['goods_desc']),
            'created_at'=>$time,
            'is_default'=>1
        ]);
        if(!$_res1)
        {
            $this->code = -1;
            $this->msg = '保存商品描述失败';
            Db::rollback();
            return false;
        }
        //商品描述
        $desc_name = $data['desc_name'];
        $desc_content = $params['desc_content'];
        $_insertData = [];
        foreach($desc_name as $k=>$v)
        {
            if(empty($v))
            {
                continue;
            }
            $_insertData[] = [
                'goods_id'=>$id,
                'desc_name'=>$v,
                'desc_content'=>$desc_content[$k],
                'created_at'=>$time,
                'sign'=>md5($desc_content[$k])
            ];
        }

        $_res2 = Db::table('shop_goods_desc')->insertAll($_insertData);
        if (!$_res2) {
            $this->code = -1;
            $this->msg = '其他描述信息保存失败';
            Db::rollback();
            return false;
        }
        // 提交事务
        Db::commit();
        return true;
    }

    /**
     * 全部数据
     */
    public function lst($page = 15)
    {
        $admin_id = session('admin_id');
        $where = [];
        //除了管理员，谁编辑的商品谁可以看
        $adminModel = new AdminM();
        $res = $adminModel->isAdmin($admin_id);
        if($res === false)
        {
            $where['g.admin_id'] = $admin_id;
        }
        //其他条件
        //未删除的
        $where['g.is_delete'] = 0;

        $data = Db::table('shop_goods')
            ->alias('g')
            ->join('shop_brand b','b.id = g.brand_id','LEFT')
            ->join('shop_goods_cat gc','gc.id = g.cat_id','LEFT')
            ->join('shop_type t','t.id = g.type_id','LEFT')
            ->join('shop_shop s','s.id = g.shop_id','LEFT')
            ->field('g.id,g.goods_name,g.goods_sn,g.ps_attr,g.psfs_id,g.sm_logo,b.name as brand_name,gc.name as cat_name,t.name as type_name,g.promote_start_date,g.promote_end_date,g.is_new,g.is_hot,g.is_best,g.is_floor,s.title as shop_name,g.is_discount,g.is_sh,g.is_on_sale,g.sort_num,g.created_at,g.updated_at')
            ->where($where)
            ->paginate($page);
        return $data;
    }

    /**
     * 修改数据
     * @param $data
     * @return bool
     */
    public function edit($data)
    {
        $res = $this->_V('edit',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        $insertData = [];
        //判断用户
        $admin_id = session('admin_id');
        //数据
        $insertData['goods_name'] = $data['goods_name'];
        $insertData['goods_sn'] = $data['goods_sn'];
        $insertData['ps_attr'] = $data['ps_attr'];
        $insertData['psfs_id'] = $data['psfs_id'];
        $insertData['brand_id'] = $data['brand_id'];
        $insertData['cat_id'] = $data['cat_id'];
        $insertData['type_id'] = $data['type_id'];
        $insertData['is_new'] = $data['is_new'];
        $insertData['is_hot'] = $data['is_hot'];
        $insertData['is_best'] = $data['is_best'];
        $insertData['is_floor'] = $data['is_floor'];
        $insertData['shop_id'] = $data['shop_id'];
        $insertData['is_discount'] = $data['is_discount'];
        $insertData['is_sh'] = 0;//下架重新审核
        $insertData['is_on_sale'] = $data['is_on_sale'];
        $insertData['sort_num'] = $data['sort_num'];

        if($data['ps_attr'] == 2)
        {
            $insertData['sheng_id'] = $data['sheng_id'];
            $insertData['shi_id'] = $data['shi_id'];
            $insertData['xian_id'] = $data['xian_id'];
            $insertData['coordinate'] = $data['coordinate'];
        }
        //时间
        if(!empty($data['promote_start_date']))
        {
            $insertData['promote_start_date'] = strtotime($data['promote_start_date']);
        }
        if(!empty($data['promote_end_date']))
        {
            $insertData['promote_end_date'] = strtotime($data['promote_end_date']);
        }
        $insertData['updated_at'] = time();
        //主图

        //处理图片
        $ret = uploadOne('logo', array(
            array(800, 800),
            array(600, 600),
            array(300, 300),
            array(100, 100),
        ));
        if($ret['ok'] == 1)
        {
            $insertData['logo'] = toQiNiu($ret['images'][0]);   // 原图地址
            $insertData['mbig_logo'] = toQiNiu($ret['images'][1]);   // 第一个缩略图地址
            $insertData['big_logo'] = toQiNiu($ret['images'][2]);   // 第二个缩略图地址
            $insertData['mid_logo'] = toQiNiu($ret['images'][3]);   // 第三个缩略图地址
            $insertData['sm_logo'] = toQiNiu($ret['images'][4]);   // 第三个缩略图地址
        }
        else if($ret['ok'] == 2)
        {
        }
        else
        {
            $this->code = -1;
            $this->msg = $ret['error'];
            return false;
        }
        $id = $data['id'];
        //启动事务
        Db::startTrans();
        //商品插入数据库
        $res = Db::table('shop_goods')->where('id',$id)->update($insertData);
        if (!$res) {
            $this->code = -1;
            $this->msg = '修改失败';
            Db::rollback();
            return false;
        }
        //属性

        /*********************处理商品属性-start******************/
        $gaid=$data['goods_attr_id'];
        $attr_value=$data['attr_value'];
//            dump($attr_value);die;
        $_i=0;
        foreach($attr_value as $k=>$v){
            foreach($v as $k1=>$v1){
                if($gaid[$_i] == ''){
                    $res = Db::table('shop_goods_attr')->insertGetId([
                        'attr_id'=>$k,
                        'attr_value'=>$v1,
                        'goods_id'=>$id,
                        'admin_id'=>$admin_id,
                    ]);
                }else {
                    $res = Db::table('shop_goods_attr')->where('id',$gaid[$_i])->setField('attr_value',$v1);
                }
                $_i++;
            }
        }
        /*********************处理商品属性-end******************/
        //图片

        /*********************处理图片相册-start******************/
        if (isset($_FILES['pic']))
        {
            $res = uploadMore('pic',array(
                array(450, 450),
                array(260, 260),
                array(66, 66),
            ));
            if(isset($res['ok']))
            {
                if($res['ok'] == 0)
                {//出现错误
                    $this->code = -1;
                    $this->msg = $res['error'];
                    Db::rollback();
                    return false;
                }
                else
                {//没有图片

                }

            }
            else
            {//上传成功
                foreach($res as $k=>$v)
                {
                    $res2 = Db::table('shop_goods_pic')->insertGetId([
                        'goods_id' => $id,
                        'pic' => toQiNiu($v['images'][0]),
                        'small_pic' => toQiNiu($v['images'][3]),
                        'mid_pic' => toQiNiu($v['images'][2]),
                        'big_pic' => toQiNiu($v['images'][1]),
                    ]);
                    if(!$res2)
                    {
                        $this->code = -1;
                        $this->msg = '报存图片到相册失败';
                        Db::rollback();
                        return false;
                    }

                }

            }
        }
        /*********************处理图片相册-end******************/


        /*********************商品描述******************/
        //获取原始数据
        $params = Request::instance()->post(false);
        $time = time();
        //获取商品描述
        $_goods_desc = Db::table('shop_goods_desc')->where(['goods_id'=>$id,'is_default'=>1,'is_usable'=>1])->field('id,sign')->find();

        if($_goods_desc['sign'] != md5($params['goods_desc']))
        {//商品描述改变
            //将原来默认的删除
            Db::table('shop_goods_desc')->where(['id'=>$_goods_desc['id']])->update(['is_usable'=>0]);
            //现将商品描述插入
            $_res1 = Db::table('shop_goods_desc')->insertGetId([
                'goods_id'=>$id,
                'desc_name'=>'商品详情',
                'desc_content'=>$params['goods_desc'],
                'sign'=>md5($params['goods_desc']),
                'created_at'=>$time,
                'is_default'=>1
            ]);
            if(!$_res1)
            {
                $this->code = -1;
                $this->msg = '修改商品描述失败';
                Db::rollback();
                return false;
            }
        }



        // 提交事务
        Db::commit();
        return true;
    }

    /**
     * 删除数据
     * @param $id
     */
    public function del($id)
    {
        return Db::table('shop_goods')->where('id',$id)->update(['is_delete'=>1]);
    }

    /**
     * 删除数据
     * @param $id
     */
    public function review($id)
    {
        return Db::table('shop_goods')->where('id',$id)->update(['is_sh'=>1]);
    }



    /**
     * 商品属性
     * @param $goods_id
     * @return array
     */
    public function getGoodsAttrByGoodsID($goods_id){

        $info = Db::table('shop_goods_attr')
                ->alias('ga')
                ->join('shop_attribute a','a.id = ga.attr_id')
                ->field('a.attr_name,ga.id,ga.attr_value')
                ->where(['ga.goods_id'=>$goods_id,'a.attr_type'=>'可选'])
                ->select();
        $data=array();
        foreach($info as $k=>$v){//把相同的名称的属性值放到一个数组
            $data[$v['attr_name']][]=$v;
        }
        return $data;
    }

    public function goods_num($data)
    {
            $admin_id = session('admin_id');
            Db::table('shop_goods_num')->where(array('goods_id'=>array('eq',$data['goods_id'])))->delete();
            //判断提交了几个属性
            $gaids=$data['goods_attr_id'];
            $goods_num=$data['goods_num'];
            $goods_price=$data['goods_price'];
            $promote_price=$data['promote_price'];
            $member_price=$data['member_price'];
            $goods_weight=$data['goods_weight'];
            $rate=count($gaids)/count($goods_num);
            $_i=0;
            foreach($goods_num as $k=>$v){
                $gaid=array();
                for($i=0;$i<$rate;$i++){
                    $gaid[]=$gaids[$_i];
                    $_i++;
                }
                sort($gaid,SORT_NUMERIC);
                $gaid=implode(',',$gaid);
                Db::table('shop_goods_num')->insertGetId(array(
                    'goods_attr_id'=>$gaid,
                    'goods_price'=>$goods_price[$k],
                    'promote_price'=>$promote_price[$k],
                    'member_price'=>$member_price[$k],
                    'goods_weight'=>$goods_weight[$k],
                    'goods_number'=>$v,
                    'goods_id'=>$data['goods_id'],
                    'admin_id'=>$admin_id,
                ));
            }

    }


}
